﻿package net.wangit.view.unit.grid;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.util.Checker;
import net.wangit.view.unit.UnitComponent;
import net.wangit.view.util.Html;

public class FormGrid extends Grid {

	public FormGrid(ActionContext ac, UnitComponent unit) {
		super(ac, unit);
	}

	public String write(ActionContext ac, MapList data) {
		if (uc.size() == 0)
			return "";
		StringBuffer html = new StringBuffer();
		if (Checker.isEmpty(data)) {
			if (!uc.isAppendInsertScript()) {
				html.append("<tr><td>");
				writeRow(ac, html, null, -1, uc.getRowCss(0));
				html.append("</td></tr>");
			}
		} else {
			for (int i = 0; i < data.size(); i++) {
				html.append("<tr id=\"").append(i).append("\"");
				Html.setVisible(html, uc.isRowsVisible());
				html.append("><td>");
				Row row = data.getRow(i);
				writeRow(ac, html, row, i, uc.getRowCss(i));
				html.append("</td></tr>");
			}

		}
		if (uc.isAppendInsertScript())
			writeInsertContent(ac, html);
		return html.toString();
	}

	protected void writeRow(ActionContext ac, StringBuffer html, Row row,
			int rowIndex, String rowCss) {
		beginTable(html);
		top.write(ac, html, row, rowIndex, rowCss);
		for (int i = 0; i < groups.size(); i++) {
			Group group = (Group) groups.get(i);
			group.write(ac, html, row, rowIndex, rowCss);
		}

		html.append("</table>");
	}

	private void writeInsertContent(ActionContext ac, StringBuffer html) {
		html.append("<tr style=\"display:none\"><td>");
		html.append("<textarea id=\"").append("_in_").append("\">");
		html.append("<tr id=temp><td>");
		writeRow(ac, html, insertRow, -1, null);
		html.append("</td></tr>");
		html.append("</textarea>");
		html.append("</td></tr>");
	}
}
